<template>
  <div class="content">
    <div ref="topContent">
      <div class="topBox">
        <div class="topLeft">关键词报表</div>
        <div class="topRight">
          <t-button theme="primary" @click="onClickExport" v-permission="['keyword:statement:export']">
            <span>导出本页</span>
            <span style="margin-left: 8px">
              <svg-icon :name="'icon-arrowTD'" class-name="arrowTD-svg-icon"></svg-icon>
            </span>
          </t-button>
        </div>
      </div>
      <div class="line"></div>
      <div class="formBox">
        <t-form v-show="!isFold" ref="form" :data="formData" :layout="'inline'" scroll-to-first-error="smooth"
          :class="isFold ? '' : 'paddingBottom'">
          <t-form-item label="选择平台" name="platform" requiredMark :label-width="68">
            <t-select v-model="formData.platform" @change="onPlatformChange" placeholder="请选择所属平台">
              <t-option key="0" label="CC-1.0" :value="0" />
              <t-option key="1" label="TNCS" :value="1" />
              <t-option key="2" label="CC-2.0" :value="2" />
            </t-select>
          </t-form-item>

          <t-form-item label="所属企业" name="company" requiredMark :label-width="68" v-if="formData.platform !== 1">
            <t-select v-model="formData.company" :filter="filterMethod" @change="onCompanyChange" placeholder="请选择所属企业">
              <t-option v-for="item in companyOptions" :key="item.id" :label="item.agencyName" :value="item.agencyId" />
            </t-select>
          </t-form-item>

          <t-form-item label="所属机构" name="org" requiredMark :label-width="68" v-if="formData.platform !== 1">
            <t-select v-model="formData.org" :filter="filterMethod" @change="onOrgChange" placeholder="请选择所属机构">
              <t-option v-for="item in orgOptions" :key="item.id" :label="item.agencyName" :value="item.agencyId" />
            </t-select>
          </t-form-item>

          <!--          TNCs 机构-->
          <t-form-item label="所属机构" name="org" :label-width="68" requiredMark v-if="formData.platform === 1">
            <t-select v-model="formData.org" :filter="filterMethod" @change="onOrgChange" placeholder="请选择所属机构">
              <!--              <t-option key="" label="全部" value=""></t-option>-->
              <t-option v-for="item in orgOptions" :key="item.id" :label="item.projectName" :value="item.id" />
            </t-select>
          </t-form-item>

          <t-form-item label="所属部门" name="branch" requiredMark :label-width="68" v-if="formData.platform !== 1">
            <t-select v-model="formData.branch" :filter="filterMethod" @change="onBranchChange" placeholder="请选择所属部门">
              <t-option v-for="item in branchOptions" :key="item.id" :label="item.agencyName" :value="item.agencyId" />
            </t-select>
          </t-form-item>

          <t-form-item class="c_time" style="width: 50%" :class="formData.platform === 1 ? 'normalForm' : ''">
            <t-space size="small" style="gap: 10px;">
              <div class="timeType">
                <span class="timeCheck" @click="timeClick('today')">今天</span>
                <span class="timeCheck" @click="timeClick('yesterday')">昨天</span>
                <span class="timeCheck" @click="timeClick('oneMonth')">一月</span>
                <span>时间</span>
              </div>
              <t-date-picker
                  v-model="formData.startTime"
                  placeholder="选择开始时间"
                  valueType="YYYY-MM-DD"
                  :disable-date="(date) => setDateStart(formData.endTime, date)"
              />
              <t-date-picker
                  v-model="formData.endTime"
                  placeholder="选择结束时间"
                  valueType="YYYY-MM-DD"
                  :disable-date="(date) => setDateEnd(formData.startTime, date)"
              />
            </t-space>
          </t-form-item>

          <t-form-item label="选择模版" name="templateId" :label-width="56"
            :class="formData.platform === 1 ? 'shortFrom' : ''">
            <t-select v-model="formData.templateId">
              <t-option :key="null" label="全部" :value="null"></t-option>
              <t-option v-for="item in templateOptions" :key="item.id" :label="item.templateName" :value="item.id" />
            </t-select>
          </t-form-item>

          <t-form-item class="formHandleBox" v-if="!isFold">
            <t-space size="small" style="gap: 10px;">
              <t-button class="queryBtn hoverBlue" @click="handleQuery(1)" v-permission="['keyword:statement:list']">查询</t-button>
              <t-button class="resetBtn hoverLightBlue" @click="handleReset">重置</t-button>
              <span class="arrowCont">
                <svg-icon @click="handleArrow" :name="'icon-arrowTD'" class-name="arrowTD-svg-icon"
                  :style="isFold === true ? '' : 'transform: rotate(180deg)'"></svg-icon>
              </span>
            </t-space>
          </t-form-item>
        </t-form>
        <!--      展开-->
        <div class="upArrow" v-show="isFold">
          <svg-icon @click="handleArrow" :name="'icon-arrowTD'" class-name="arrowTD-svg-icon"
            :style="isFold === true ? '' : 'transform: rotate(180deg)'"></svg-icon>
        </div>
      </div>
    </div>

    <div class="tableBox">
      <div style="position: relative">
        <t-table :loading="isLoading" :height="tableHeight" row-key="id" :columns="tableState.columns"
          :data="tableState.tableData">
          <template #call_rate>
            <div class="funnel" style="display: flex; align-items: center">
              <span style="margin-right: 5px">触发通话率</span>
              <t-tooltip content="触发通话量/录音总量">
                <svg-icon :name="'icon-exclMark'" class-name="exclMark-svg-icon"></svg-icon>
              </t-tooltip>
            </div>
          </template>

          <template #call_num>
            <div class="funnel" style="display: flex; align-items: center">
              <span style="margin-right: 5px">触发通话量</span>
              <svg-icon @click="onCallVolumeClick" :name="'icon-sort'" class-name="sort-svg-icon"></svg-icon>
            </div>
          </template>

          <template #call_num_tool>
            <div class="funnel" style="display: flex; align-items: center">
              <span style="margin-right: 5px">触发量</span>
              <svg-icon @click="onFrequencyClick" :name="'icon-sort'" class-name="sort-svg-icon"></svg-icon>
            </div>
          </template>
        </t-table>
        <div class="emptyBox" v-if="tableState.tableData.length === 0">
          <svg-icon :name="'icon-emptyTable'" class-name="emptyTable-svg-icon"></svg-icon>
          <span>暂无数据</span>
        </div>
      </div>
    </div>

    <div class="footerBox">
      <t-pagination v-model="current" v-model:pageSize="pageSize" :pageSizeOptions="[10, 20, 30, 50]" :total="totalNum"
        size="small" show-jumper @page-size-change="onPageSizeChange" @current-change="onCurrentChange" />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { MessagePlugin } from "tdesign-vue-next";
import { debounce } from "../../utils/tools";
import {cc0AgencyList, cc0SeatsList, cc2AgencyList, getTemplate, TNCsAgencyList} from "../../api/commonApi";
import cache from '@/utils/cache.js'
import { keywordStatementList, keywordStatementExport } from "../../api/qualityForms";
import { usePageStore } from '@/pinia/page.js'
const store = usePageStore()
const pageInstance = getCurrentInstance()
import { getTypeData, setDateStart, setDateEnd } from '@/hooks/useCheckDate.js'
// form 表单
const formData = reactive({
  platform: null,
  company: '',
  org: '',
  branch: '',
  startTime: '',
  endTime: '',
  templateId: null,
  frequencyType: 0, // 触发量排序
  callVolumeType: 0, // 平均分排序
});

const companyOptions = ref([]) // 企业options
const orgOptions = ref([]) // 机构options
const branchOptions = ref([]) // 部门options
const seatsOptions = ref([]) // 座席options
const isLoading = ref(false)
// 选择平台事件
const onPlatformChange = (type) => {
  store.setFormCondition(type, '', '', '')
  formData.company = ''
  companyOptions.value = []
  formData.org = ''
  orgOptions.value = []
  formData.branch = ''
  branchOptions.value = []

  // handleReset()
  getCompanyList(type)
}
const getCompanyList = (type) => {
  if (type === 0) { // 企业请求 1.0 接口
    let data = {
      agencyId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
    }
    cc0AgencyList(data).then(res => {
      companyOptions.value = res.data
    })
  } else if (type === 1) { // 机构请求 TNCs 接口
    TNCsAgencyList().then(res => {
      orgOptions.value = res.data
    })
  } else if (type === 2) { // 企业请求2.0 接口
    let data = {
      agencyId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
    }
    cc2AgencyList(data).then(res => {
      companyOptions.value = res.data
    })
  }
}
// 选择企业事件
const onCompanyChange = (type) => {
  store.setFormCondition(formData.platform, type, '', '')
  formData.org = ''
  orgOptions.value = []
  formData.branch = ''
  branchOptions.value = []
  // 获取机构options
  if(formData.platform === 0) {
    getOrgList(type)
  } else if (formData.platform === 2) {
    getOrgList2(type)
  }
}
const getOrgList = (type) => {
  let data = {
    agencyId: type
  }
  cc0AgencyList(data).then(res => {
    orgOptions.value = res.data
  })
}
const getOrgList2 = (type) => {
  let data = {
    agencyId: type
  }
  cc2AgencyList(data).then(res => {
    orgOptions.value = res.data
  })
}
// 机构选择事件
const onOrgChange = (type) => {
  store.setFormCondition(formData.platform, formData.company, type, '')
  formData.branch = ''
  branchOptions.value = []
  if(formData.platform === 0) {
    getBranchList(type)
  } else if (formData.platform === 2) {
    getBranchList2(type)
  }
}
const getBranchList = (type) => {
  let data = {
    agencyId: type
  }
  cc0AgencyList(data).then(res => {
    branchOptions.value = res.data
  })
}
const getBranchList2 = (type) => {
  let data = {
    agencyId: type
  }
  cc2AgencyList(data).then(res => {
    branchOptions.value = res.data
  })
}
// 部门选择事件
const onBranchChange = (type) => {
  store.setFormCondition(formData.platform, formData.company, formData.org, type)
}
// 导出
const onClickExport = () => {
  let data = {
    pageNo: current.value,
    pageSize: pageSize.value,
    ...formData
  }
  data.startTime = data.startTime + ' 00:00:00'
  data.endTime = data.endTime + ' 23:59:59'

  keywordStatementExport(data).then(res => {
    const url = URL.createObjectURL(res) //把blob对象转成一个url
    //创建一个a标签
    const a = document.createElement("a");
    a.href = url; //给a标签上的href属性加上地址
    a.download = "关键词报表导出.xlsx"; //下载名称
    document.body.appendChild(a); //将a标签添加到文档对象中
    a.click(); //调点击事件
    document.body.removeChild(a); // 一次性的，用完就删除a标签
  }).catch(error => {
    console.log('关键词报表导出', error)
  })
}

const handleQuery = (num) => {
  if (formData.platform === 0 || formData.platform === 2) { // 1.0 | 2.0
    if (formData.company === '') return MessagePlugin.error('请选择企业！')
    if (formData.org === '') return MessagePlugin.error('请选择机构！')
    if (formData.branch === '') return MessagePlugin.error('请选择部门！')

    formData.asrProjectId = formData.branch
    formData.projectId = JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
    let data = {
      pageNo: num === 1 ? 1 :  current.value,
      pageSize: pageSize.value,
      ...formData
    }
    data.startTime = data.startTime + ' 00:00:00'
    data.endTime = data.endTime + ' 23:59:59'
    isLoading.value = true
    keywordStatementList(data).then(res => {
      // console.log('key word list', res)
      tableState.tableData = res.data.list ? res.data.list : []
      res.data.list.forEach((item) => {
        item.callRatio = item.callRatio + '%'
      })
      tableState.tableData = res.data.list;
      current.value = res.data['currPage']
      pageSize.value = res.data['pageSize']
      totalNum.value = res.data['totalCount']
      isLoading.value = false
    }).catch(error => {
      isLoading.value = false
    })
  } else if (formData.platform === 1) { // TNCs
    if (formData.org === '') return MessagePlugin.error('请选择机构！')
    formData.asrProjectId = formData.org
    formData.projectId = JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
    let data = {
      pageNo: current.value,
      pageSize: pageSize.value,
      ...formData
    }
    data.startTime = data.startTime + ' 00:00:00'
    data.endTime = data.endTime + ' 23:59:59'
    isLoading.value = true
    keywordStatementList(data).then(res => {
      res.data.list.forEach((item) => {
        item.callRatio = item.callRatio + '%'
      })
      tableState.tableData = res.data.list;
      current.value = res.data['currPage']
      pageSize.value = res.data['pageSize']
      totalNum.value = res.data['totalCount']
      isLoading.value = false
    }).catch(error => {
      isLoading.value = false
    })
  }
};
// 重置
const handleReset = () => {
  timeClick('today')
  formData.templateId = null
}
let isFold = ref(false)
const handleArrow = () => {
  isFold.value = !isFold.value
}

//table
const tableState = reactive({
  tableData: [],
  columns: [
    { colKey: 'keyword', title: '关键词', ellipsis: true },
    { colKey: 'wordName', title: '所属词类', ellipsis: true },
    { colKey: 'wordRecords', title: 'call_num', ellipsis: true },
    { colKey: 'callRatio', title: 'call_rate' },
    { colKey: 'frequency', title: 'call_num_tool', ellipsis: true },
  ],
})

// 触发量排序
const frequencyFlag = ref(false)
const onFrequencyClick = () => {
  formData.callVolumeType = 0
  frequencyFlag.value = !frequencyFlag.value
  formData.frequencyType = frequencyFlag.value ? 1 : 2
  handleQuery()
}
// 通话量类型排序
const callVolumeFlag = ref(false)
const onCallVolumeClick = () => {
  formData.frequencyType = 0
  callVolumeFlag.value = !callVolumeFlag.value
  formData.callVolumeType = callVolumeFlag.value ? 1 : 2
  handleQuery()
}

// table 高度变化
const tableHeight = ref(0)
const getTableHeight = () => {
  nextTick(() => {
    const otherHeight = pageInstance.refs.topContent.offsetHeight
    const windowHeight = window.innerHeight
    tableHeight.value = windowHeight - otherHeight - 162
    // console.log(tableHeight.value)
  })
}
watch(() => isFold.value, (newVal, oldVal) => {
  getTableHeight()
})

// window窗口 变化
const getWindowInfo = () => {
  const info = {
    width: window.innerWidth,
    height: window.innerHeight
  }
  // console.log(info)
  getTableHeight()
}
const resizeInfo = debounce(getWindowInfo, 0)

// 获取模版list
const templateOptions = ref([])
const getTemplateOptions = () => {
  let id = JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
  getTemplate(id).then(res => {
    if (res.code === 0) {
      templateOptions.value = res.data
    }
  })
}

onMounted(() => {
  getTableHeight()
  window.addEventListener('resize', resizeInfo);
  getTemplateOptions()
  defaultSelection()
  // 时间默认当天
  timeClick('today')
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeInfo);
})

// 有值默认选中
const defaultSelection = () => {
  let formState = store.quality_form_id
  if(formState.platform !== null) { // 获取企业
    getCompanyList(formState.platform)
    formData.platform = formState.platform
  } else {
    onPlatformChange(0)
  }
  if(formState.company) { // 获取机构
    if(formData.platform === 0) {
      getOrgList(formState.company)
    } else if (formData.platform === 2) {
      getOrgList2(formState.company)
    }
    formData.company = formState.company
  }
  if(formState.org) { // 获取部门
    if(formData.platform === 0) {
      getBranchList(formState.org)
    } else if (formData.platform === 2) {
      getBranchList2(formState.org)
    }
    formData.org = formState.org
  }
  if(formState.branch) {
    formData.branch = formState.branch
    timeClick('today')
    handleQuery()
  }
}

// 时间选择事件
const timeClick = (type) => {
  formData.startTime = getTypeData(type, false).startTime
  formData.endTime = getTypeData(type, false).endTime
}

// 分页
const current = ref(1);
const pageSize = ref(10);
const totalNum = ref(0)
const onPageSizeChange = (size) => {
  pageSize.value = size
  handleQuery()
};
const onCurrentChange = (index, pageInfo) => {
  current.value = index
  handleQuery()
};

const filterMethod = (search, option) => {
  return option.label.indexOf(search) !== -1 || option.value.indexOf(search) !== -1
};
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  //overflow: hidden;
  padding: 8px;
  background-color: #EBECED !important;
}

.topBox {
  height: 65px;
  display: flex;
  padding: 20px 20px 17px 20px;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px 4px;
  .topLeft {
    font-size: 16px;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
  }

  .topRight {
    margin-left: auto;

    :deep(.t-button) {
      width: 88px;
      height: 28px;
      opacity: 1;
      border-radius: 3px;
      background: rgba(227, 238, 255, 1);
      border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
      padding: 0;
      font-size: 12px;
      font-weight: 400;
      color: rgba(30, 117, 254, 1);
    }
    :deep(.t-button):hover {
      background: var(--Brand-Brand1-Light, #EDF2FD) !important;
      color: var(--Brand-Brand6-Hover, #458DFF) !important;
      border: 1px solid var(--Brand-Brand6-Hover, #458DFF) !important;
    }

    .arrowTD-svg-icon {
      height: 16px;
      width: 16px;
      cursor: pointer;
      display: inline-block;
      vertical-align: middle;
    }
  }
}

.line {
  height: 0;
  opacity: 1;
  background: rgba(204, 204, 204, 1);
  border: 1px solid rgba(239, 242, 245, 1);
  margin: 0 20px;
}

.formBox {
  padding: 0 20px;
  background-color: rgba(255, 255, 255, 1);

  :deep(.t-form) {
    padding: 20px 0 20px 0;

    .t-form-inline {
      row-gap: 16px !important;
    }

    .t-form__item {
      width: 25%;
      height: 28px;
      margin-right: 0 !important;
      padding-right: 10px;

      .t-range-input {
        height: 28px;
      }

      .t-form__label--right {
        text-align: left;
        padding-right: 0;
        font-size: 12px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.9);
      }

      .t-select__wrap {
        .t-input {
          height: 28px;
        }
      }
    }

    .t-form__item:nth-child(4) {
      padding-right: 0;
    }

    .c_time {
      .t-form__label--right {
        display: none
      }

      .t-form__controls {
        margin-left: 0 !important;
      }

      .t-space {
        width: 100%;

        .timeCheck {
          font-size: 12px;
          font-weight: 400;
          color: rgba(30, 117, 254, 1);
          cursor: pointer;
        }
      }

      .t-space-item:nth-child(1) {
        width: 126px;
      }

      .t-space-item:nth-child(2) {
        width: calc((100% - 146px) / 2);
      }

      .t-space-item:nth-child(3) {
        width: calc((100% - 146px) / 2);
      }

      .t-date-picker {
        height: 28px;
        width: 100%;

        .t-input {
          height: 28px;
        }
      }

      .timeType {
        float: left;
        width: 126px;
        text-align: left;
        height: 28px;
        line-height: 28px;

        span {
          margin-right: 10px;
          font-size: 12px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.9);
        }

        span:nth-child(4) {
          margin-right: 0;
        }
      }
    }

    .formHandleBox {
      margin-left: auto;
      text-align: right;
      padding-right: 0;

      .t-space {
        margin-left: auto;
        justify-content: center;
        align-items: center;

        .queryBtn {
          border: none;
          width: 56px;
          height: 30px;
          opacity: 1;
          border-radius: 3px;
          background: rgba(30, 117, 254, 1);
          font-size: 12px;
          font-weight: 400;
          color: rgba(255, 255, 255, 1);
          text-align: center;
        }

        .resetBtn {
          width: 56px;
          height: 30px;
          opacity: 1;
          border-radius: 3px;
          background: rgba(236, 242, 254, 1);
          border: 0.5px solid rgba(30, 117, 254, 1);
          font-size: 12px;
          font-weight: 400;
          color: rgba(30, 117, 254, 1);
          text-align: center;
        }

        .arrowCont {
          display: flex;
          justify-content: center;
          align-items: center;

          span {
            font-size: 12px;
            font-weight: 500;
            color: rgba(138, 138, 138, 1);
          }

          .arrowTD-svg-icon {
            height: 16px;
            width: 16px;
            cursor: pointer;
          }
        }
      }

      .t-form__controls {
        margin-left: 0 !important;
      }
    }
  }

  .upArrow {
    text-align: right;
    height: 20px;

    .arrowTD-svg-icon {
      height: 16px;
      width: 16px;
      cursor: pointer;
    }
  }
}

.tableBox {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;

  :deep(.t-table__header) {
    tr {
      th {
        padding: 7px 10px;
        box-sizing: border-box;
      }

      th:nth-child(1) {
        padding-left: 70px;
      }
    }

  }

  :deep(.t-table__body) {
    tr {
      td {
        padding: 6px 10px;
        box-sizing: border-box;
      }

      td:nth-child(1) {
        padding-left: 70px;
      }
    }
  }

  .exclMark-svg-icon {
    width: 12px;
    height: 12px;
    cursor: pointer;
  }

  .sort-svg-icon {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }

  :deep(.custom-cell-select) {
    padding-right: 0 !important;
  }

  :deep(.custom-cell-index) {
    padding-left: 0 !important;
  }
}

:deep(.t-table__empty) {
  display: none;
}

.emptyBox {
  position: absolute;
  height: 116px;
  width: 69px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;

  .emptyTable-svg-icon {
    height: 62px;
    width: 69px;
  }

  span {
    font-size: 12px;
    font-weight: 400;
    color: rgba(92, 91, 91, 1);
  }
}

.footerBox {
  background-color: rgba(255, 255, 255, 1);
  width: calc(100% - 16px);
  position: absolute;
  bottom: 8px;
  overflow: hidden;
  border-radius: 0 0 4px 4px;
}

.shortFrom {
  padding-right: 10px !important;
}

.normalForm {
  padding-right: 0 !important;
}
</style>
